package com.sywb.chuangyebao.contract;

import android.app.Activity;
import android.graphics.Color;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.Page;
import com.sywb.chuangyebao.bean.User;
import com.sywb.chuangyebao.bean.UserAnswer;
import com.sywb.chuangyebao.bean.UserFriend;
import com.sywb.chuangyebao.utils.GlideUtils;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.utils.Utils;
import com.sywb.chuangyebao.view.QAndADetailActivity;
import com.sywb.chuangyebao.view.TopicActivity;
import com.sywb.chuangyebao.widget.ColorTrackTabLayout;
import com.sywb.chuangyebao.widget.RichTextView;

import org.bining.footstone.adapter.BasePagerAdapter;
import org.bining.footstone.adapter.BaseRecyclerAdapter;
import org.bining.footstone.adapter.BaseRecyclerDivider;
import org.bining.footstone.adapter.ViewHolderHelper;
import org.bining.footstone.adapter.listener.OnItemChildClickListener;
import org.bining.footstone.adapter.listener.OnItemClickListener;
import org.bining.footstone.adapter.listener.OnLoadMoreListener;
import org.bining.footstone.mvp.IView;
import org.bining.footstone.presenter.BasePresenter;
import org.bining.footstone.utils.ScreenUtils;
import org.bining.footstone.utils.ToastUtils;
import org.bining.footstone.view.BaseActivity;
import org.bining.footstone.widget.PullToRefreshView;

import java.util.ArrayList;
import java.util.List;

/**
 * 优惠活动
 */
public interface FriendsContract {

    interface FriendView extends IView {

        int getQuestionId();
    }

    class Presenter extends BasePresenter<FriendView> {

        private List<BaseRecyclerAdapter> friendAdapters;
        private List<RelativeLayout> commonNoDatas;
        private int[] pageNos;
        private List<PullToRefreshView> commonRefreshs;
        private ViewPager viewPager;

        @Override
        public void onStart() {
            friendAdapters = new ArrayList<>();
            commonNoDatas = new ArrayList<>();
            commonRefreshs = new ArrayList<>();
        }

        /**
         * 初始化View
         *
         * @param type //0关注 粉丝  1已回答 待回答 2创业万里行  3推荐 好友
         */
        public void initTabView(int type, ViewPager viewPager, ColorTrackTabLayout tlIndex) {
            this.viewPager = viewPager;
            int padding = mActivity.getResources().getDimensionPixelSize(R.dimen.dp_10);
            switch (type) {
                case 0:
                    initThreeView(type, new String[]{mActivity.getString(R.string.friends), mActivity.getString(R.string.fans), mActivity.getString(R.string.topic)});
                    break;
                case 1:
                    initDoubleView(type, new String[]{mActivity.getString(R.string.answered), mActivity.getString(R.string.wait_answer)});
                    break;
                case 3:
                    initDoubleView(type, new String[]{mActivity.getString(R.string.recommend), mActivity.getString(R.string.friends)});
                    break;
            }

            viewPager.setCurrentItem(0);
            tlIndex.setTabPaddingLeftAndRight(padding, padding);
            tlIndex.setupWithViewPager(viewPager);
//            tlIndex.post(new Runnable() {
//                @Override
//                public void run() {
//                    //设置最小宽度，使其可以在滑动一部分距离
//                    ViewGroup slidingTabStrip = (ViewGroup) tlIndex.getChildAt(0);
//                    slidingTabStrip.setMinimumWidth(slidingTabStrip.getMeasuredWidth());
//                }
//            });
            //隐藏指示器
            tlIndex.setSelectedTabIndicatorHeight(6);
        }

        /**
         * 初始化两个tab的页面
         *
         * @param type   //0关注 粉丝  1已回答 待回答 2创业万里行  3推荐 好友
         * @param titles tab title数组
         */
        private void initDoubleView(int type, String[] titles) {
            pageNos = new int[2];
            pageNos[0] = 1;
            pageNos[1] = 1;
            List<View> viewList = new ArrayList<>();
            viewList.add(initPage(type, 0));
            viewList.add(initPage(type, 1));
            viewPager.setAdapter(new MyPagerAdapter(viewList, titles));
            viewPager.setOffscreenPageLimit(viewList.size());
        }

        private void initThreeView(int type, String[] titles) {
            pageNos = new int[3];
            pageNos[0] = 1;
            pageNos[1] = 1;
            pageNos[2] = 1;
            List<View> viewList = new ArrayList<>();
            viewList.add(initPage(type, 0));
            viewList.add(initPage(type, 1));
            viewList.add(initPage(type, 2));
            viewPager.setAdapter(new MyPagerAdapter(viewList, titles));
            viewPager.setOffscreenPageLimit(viewList.size());
        }

        private View initPage(int type, final int position) {
            View view = mActivity.getLayoutInflater().inflate(R.layout.layout_recycler_refresh, null);
            RecyclerView commonRecycler = view.findViewById(R.id.common_recycler);
            RelativeLayout commonNoData = view.findViewById(R.id.common_nodata);
            commonNoDatas.add(commonNoData);
            PullToRefreshView commonRefresh = view.findViewById(R.id.common_refresh);
            commonRefreshs.add(commonRefresh);

            commonRecycler.setLayoutManager(new LinearLayoutManager(mActivity));
            BaseRecyclerAdapter adapter = null;
            switch (type) {
                case 0:
                default:
                    adapter = new FriendAdapter(mActivity, position);
                    BaseRecyclerDivider divider = new BaseRecyclerDivider();
                    divider.setDivider(ScreenUtils.dp2px(1));
                    divider.setColor(ContextCompat.getColor(mActivity, R.color.windowBackground));
                    commonRecycler.addItemDecoration(divider);
                    commonRecycler.setAdapter(adapter);
                    friendAdapters.add(adapter);

                    commonRefresh.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
                        @Override
                        public void onRefresh(PullToRefreshView pullToRefreshView) {
                            onStartRefresh();
                            pageNos[viewPager.getCurrentItem()] = 1;
                            getFriendsList(viewPager.getCurrentItem());
                        }
                    });

                    adapter.openLoadMore(R.layout.layout_loading, Constants.PAGESIZE);
                    adapter.setOnLoadMoreListener(new OnLoadMoreListener() {
                        @Override
                        public void onLoadMoreClick() {
                            onStartLoadMore();
                            pageNos[viewPager.getCurrentItem()]++;
                            getFriendsList(viewPager.getCurrentItem());
                        }
                    });

                    final FriendAdapter friendAdapter = (FriendAdapter) adapter;
                    adapter.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, int i) {
                            UserFriend userFriend = friendAdapter.getItem(i);
                            if (viewPager.getCurrentItem() == 2) {
                                mView.advance(TopicActivity.class, userFriend.topic_id);
                            } else {
//                                mView.advance(UserIndexActivity.class, viewPager.getCurrentItem() == 0 ? userFriend.topic_id : userFriend.from_uid);

                                Utils.goUserIndex(mView, viewPager.getCurrentItem() == 0 ? userFriend.topic_id : userFriend.from_uid);
                            }
                        }
                    });

                    onStartAsync();
                    getFriendsList(position);
                    break;
                case 1:
                    switch (position) {
                        case 0:
                            adapter = new AnsweredAdapter(mActivity);
                            final AnsweredAdapter answeredAdapter = (AnsweredAdapter) adapter;
                            adapter.setOnItemClickListener(new OnItemClickListener() {
                                @Override
                                public void onItemClick(View view, int i) {
                                    mView.advance(QAndADetailActivity.class, answeredAdapter.getItem(i).question_id);
                                }
                            });

                            break;
                        case 1:
                            adapter = new AnswerAdapter(mActivity);
                            final AnswerAdapter answerAdapter = (AnswerAdapter) adapter;
                            adapter.setOnItemClickListener(new OnItemClickListener() {
                                @Override
                                public void onItemClick(View view, int i) {
                                    mView.advance(QAndADetailActivity.class, answerAdapter.getItem(i).question_id);
                                }
                            });
                            break;
                    }

                    commonRecycler.setAdapter(adapter);
                    friendAdapters.add(adapter);

                    commonRefresh.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
                        @Override
                        public void onRefresh(PullToRefreshView pullToRefreshView) {
                            onStartRefresh();
                            pageNos[viewPager.getCurrentItem()] = 1;
                            getAnswerList(viewPager.getCurrentItem());
                        }
                    });

                    assert adapter != null;
                    adapter.openLoadMore(R.layout.layout_loading, Constants.PAGESIZE);
                    adapter.setOnLoadMoreListener(new OnLoadMoreListener() {
                        @Override
                        public void onLoadMoreClick() {
                            onStartLoadMore();
                            pageNos[viewPager.getCurrentItem()]++;
                            getAnswerList(viewPager.getCurrentItem());
                        }
                    });

                    onStartAsync();
                    getAnswerList(position);
                    break;
                case 3:
                    adapter = new InviteAdapter(mActivity);
                    commonRecycler.setAdapter(adapter);
                    friendAdapters.add(adapter);

                    commonRefresh.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
                        @Override
                        public void onRefresh(PullToRefreshView pullToRefreshView) {
                            onStartRefresh();
                            pageNos[viewPager.getCurrentItem()] = 1;
                            getInviteList(viewPager.getCurrentItem());
                        }
                    });

                    adapter.openLoadMore(R.layout.layout_loading, Constants.PAGESIZE);
                    adapter.setOnLoadMoreListener(new OnLoadMoreListener() {
                        @Override
                        public void onLoadMoreClick() {
                            onStartLoadMore();
                            pageNos[viewPager.getCurrentItem()]++;
                            getInviteList(viewPager.getCurrentItem());
                        }
                    });

                    final InviteAdapter inviteAdapter = (InviteAdapter) adapter;
                    adapter.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, int i) {
//                            mView.advance(UserIndexActivity.class, inviteAdapter.getItem(i).user_id);
                            Utils.goUserIndex(mView, inviteAdapter.getItem(i).user_id);
                        }
                    });

                    onStartAsync();
                    getInviteList(position);
                    break;
            }
            return view;
        }


        private void onStartRefresh() {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    onEndRefresh();
                }
            }, 2000);
        }

        private void onEndRefresh() {
            commonRefreshs.get(viewPager.getCurrentItem()).refreshFinish(true);
        }

        private void onStartLoadMore() {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    onEndLoadMore();
                }
            }, 2000);
        }

        private void onEndLoadMore() {
            commonRefreshs.get(viewPager.getCurrentItem()).loadmoreFinish(true);
        }

        private void isNoData(int position) {
            commonNoDatas.get(position).setVisibility(friendAdapters.get(position).getDataCount() == 0 ? View.VISIBLE : View.GONE);
        }

        private void getInviteList(final int position) {
            HttpUtils.listUserTutor(0, Constants.PAGESIZE, pageNos[position], position != 0, -1, mView.getQuestionId(), "", position == 1 ? "follow" : "", new HttpCallback<Page<User>>() {

                @Override
                public void onSuccess(Page<User> userPage) {
                    refreshPage(userPage, position);
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    showMessage(strMsg);
                    refreshPage(null, position);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                }
            });
        }


        private void getFriendsList(final int position) {
            String type = null;
            switch (position) {
                case 0:
                    type = "my_friend";
                    break;
                case 1:
                    type = "my_fans";
                    break;
                case 2:
                    type = "my_follow_topic";
                    break;
            }

            HttpUtils.followList(type, pageNos[position], new HttpCallback<List<UserFriend>>() {

                @Override
                public void onSuccess(List<UserFriend> userFriends) {
                    refreshList(userFriends, position);
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    refreshList(null, position);
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                }
            });
        }


        private <T> void refreshList(List<T> list, int position) {
//            mView.hideProgress();
            int pageNo = pageNos[position];
            BaseRecyclerAdapter recyclerAdapter = friendAdapters.get(position);
            if (pageNo == 1) {
                onEndRefresh();
                recyclerAdapter.clearDatas();
            } else {
                onEndLoadMore();
            }

            if (isNotNull(list)) {
                recyclerAdapter.notifyDataChangedAfterLoadMore(list);
            }
            isNoData(position);
        }

        private <T> void refreshPage(Page<T> pageInfo, int position) {
//            mView.hideProgress();
            int pageNo = pageNos[position];
            BaseRecyclerAdapter adapter = friendAdapters.get(position);
            if (pageNo == 1) {
                onEndRefresh();
                adapter.clearDatas();
            } else {
                onEndLoadMore();
                adapter.closeLoadMore();
            }

            if (pageInfo != null) {
                adapter.setLoadMoreEnable(pageInfo.page < pageInfo.lastPageNo);
                if (pageInfo.list != null) {
                    adapter.notifyDataChangedAfterLoadMore(pageInfo.list);
                }
            }
            isNoData(position);
        }


        public void getAnswerList(final int position) {
            HttpUtils.wendaList(position == 0, pageNos[position], new HttpCallback<List<UserAnswer>>() {
                @Override
                public void onSuccess(List<UserAnswer> userAnswers) {
                    refreshList(userAnswers, position);
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    refreshList(null, position);
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                }
            });
        }


        class MyPagerAdapter extends BasePagerAdapter {

            private String[] titles;

            public MyPagerAdapter(List<View> viewList, String[] titles) {
                super(viewList);
                this.titles = titles;
            }


            @Override
            public CharSequence getPageTitle(int position) {
                return titles[position];
            }
        }

        class FriendAdapter extends BaseRecyclerAdapter<UserFriend> implements OnItemChildClickListener {

            private int type;

            FriendAdapter(Activity activity, int type) {
                super(activity, R.layout.item_friend);
                this.type = type;
            }

            @Override
            protected void setItemData(ViewHolderHelper viewHolderHelper, int position, UserFriend model) {
                viewHolderHelper.setOnItemChildClickListener(this);
                viewHolderHelper.setItemChildClickListener(R.id.tv_add_focus);

                ImageView imageView = viewHolderHelper.getView(R.id.iv_friend_face);
                GlideUtils.getCircleImageToUrl(mActivity, model.avatar_s, imageView);

                //设置提问人角色类型

                Utils.setUserRoleIcon((ImageView) viewHolderHelper.getView(R.id.iv_user_type), model.user_role);
                Utils.setUserRoleText((TextView) viewHolderHelper.getView(R.id.tv_friend_type), model.user_role);

                viewHolderHelper.setText(R.id.tv_friend_name, type == 2 ? String.format("#%s#", model.nickname) : model.nickname)
                        .setText(R.id.tv_friend_sign, model.brief_intro)
                        .setVisibility(R.id.ll_sign, TextUtils.isEmpty(model.brief_intro) ? View.GONE : View.VISIBLE);


                TextView tvFollow = viewHolderHelper.getView(R.id.tv_add_focus);
                if (model.status) {
                    //已关注
                    tvFollow.setText(R.string.btn_attentioned);
                    tvFollow.setBackgroundResource(R.drawable.round3_line_gray_white);
                    tvFollow.setTextColor(ContextCompat.getColor(mActivity, R.color.colorGray));
                } else {
                    tvFollow.setText(R.string.add_focus);
                    tvFollow.setBackgroundResource(R.drawable.round_pie_msg_unread);
                    tvFollow.setTextColor(ContextCompat.getColor(mActivity, R.color.colorLight));
                }

//                Utils.setFolllowView(mActivity, model.status, tvFollow);
            }

            @Override
            public void onItemChildClick(View view, int i) {
                if (!((BaseActivity) mActivity).isCanClick(view)) return;
                final UserFriend userFriend = mDatas.get(i);
                switch (view.getId()) {
                    case R.id.tv_add_focus:
                        //判断是否登录
                        if (!Utils.checkIsLogin()) {
                            return;
                        }

                        HttpUtils.follow(type == 1 ? userFriend.from_uid : userFriend.topic_id, type == 2 ? Constants.TOPIC_TYPE_TOPIC : Constants.TOPIC_TYPE_USER, !userFriend.status, new HttpCallback<Object>() {

                            @Override
                            public void onStart() {
                                super.onStart();
                                onStartAsync();
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                onFinishAsync();
                            }

                            @Override
                            public void onSuccess(Object s) {
                                ToastUtils.show(mContext, userFriend.status ? "取消关注" : "关注成功");
                                userFriend.status = !userFriend.status;
                                notifyDataSetChanged();
                            }

                            @Override
                            public void onError(String strMsg) {
                                super.onError(strMsg);
                                showMessage(strMsg);
                            }
                        });
                        break;
                }
            }
        }

        class AnswerAdapter extends BaseRecyclerAdapter<UserAnswer> implements OnItemChildClickListener {

            AnswerAdapter(Activity activity) {
                super(activity, R.layout.item_wait_answer);
            }

            @Override
            protected void setItemData(ViewHolderHelper viewHolderHelper, int position, final UserAnswer model) {
                //设置富文本
                RichTextView richTextView = viewHolderHelper.getView(R.id.richTextView);
                richTextView.setMaxLines(3);
                richTextView.setExpandView(true);
                richTextView.setRichText(model.title, model.richInfoList);
                richTextView.setOnLinkClickListener(new RichTextView.OnLinkClickListener() {
                    @Override
                    public void onAtClick(RichTextView richTextView, Object userId) {
//                        mView.advance(UserIndexActivity.class, userId);
                        Utils.goUserIndex(mView, (Integer) userId);
                    }

                    @Override
                    public void onTopicClick(RichTextView richTextView, Object topicId) {
                        //若当前已为话题聚合页，则不跳转
                        mView.advance(TopicActivity.class, topicId);
                    }

                    @Override
                    public void onEmojiClick(RichTextView richTextView, Object emoji) {

                    }

                    @Override
                    public void onUrlClick(RichTextView richTextView, Object url) {

                    }

                    @Override
                    public void onAllClick(RichTextView richTextView) {
                        mView.advance(QAndADetailActivity.class, model.question_id);
                    }
                });
            }

            @Override
            public void onItemChildClick(View view, int i) {
                if (!((BaseActivity) mActivity).isCanClick(view)) return;
            }
        }

        class AnsweredAdapter extends BaseRecyclerAdapter<UserAnswer> implements OnItemChildClickListener {

            AnsweredAdapter(Activity activity) {
                super(activity, R.layout.item_answered);
            }

            @Override
            protected void setItemData(ViewHolderHelper viewHolderHelper, int position, final UserAnswer model) {
//                viewHolderHelper.setText(R.id.tv_question_name, model.title);
                TextView textView = viewHolderHelper.getView(R.id.tv_answer);
//                textView.setText(Html.fromHtml("<font color=\'#4D6898\'>回答：</font>" + model.content));

                String content = "回答：" + model.content;

                SpannableString spannableString = new SpannableString(content);
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#4D6898")), 0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                textView.setText(spannableString);

                //设置富文本
                RichTextView richTextView = viewHolderHelper.getView(R.id.richTextView);
                richTextView.setMaxLines(3);
                richTextView.setExpandView(true);
                richTextView.setRichText(model.title, model.richInfoList);
                richTextView.setOnLinkClickListener(new RichTextView.OnLinkClickListener() {
                    @Override
                    public void onAtClick(RichTextView richTextView, Object userId) {
//                        mView.advance(UserIndexActivity.class, userId);
                        Utils.goUserIndex(mView, (Integer) userId);
                    }

                    @Override
                    public void onTopicClick(RichTextView richTextView, Object topicId) {
                        //若当前已为话题聚合页，则不跳转
                        mView.advance(TopicActivity.class, topicId);
                    }

                    @Override
                    public void onEmojiClick(RichTextView richTextView, Object emoji) {

                    }

                    @Override
                    public void onUrlClick(RichTextView richTextView, Object url) {

                    }

                    @Override
                    public void onAllClick(RichTextView richTextView) {
                        mView.advance(QAndADetailActivity.class, model.question_id);
                    }
                });
            }

            @Override
            public void onItemChildClick(View view, int i) {
                if (!((BaseActivity) mActivity).isCanClick(view)) return;
            }
        }

        public class InviteAdapter extends BaseRecyclerAdapter<User> implements OnItemChildClickListener {

            InviteAdapter(Activity activity) {
                super(activity, R.layout.item_friend);
            }

            @Override
            protected void setItemData(ViewHolderHelper viewHolderHelper, int position, User model) {
                viewHolderHelper.setVisibility(R.id.tv_add_focus, View.GONE);
                viewHolderHelper.setVisibility(R.id.tv_invite, View.VISIBLE);
                viewHolderHelper.setOnItemChildClickListener(this);
                viewHolderHelper.setItemChildClickListener(R.id.tv_invite);

                ImageView imageView = viewHolderHelper.getView(R.id.iv_friend_face);
                GlideUtils.getCircleImageToUrl(mActivity, model.avatar, imageView);

                //设置提问人角色类型
                TextView tvUserType = viewHolderHelper.getView(R.id.tv_friend_type);
                Utils.setUserRoleIcon((ImageView) viewHolderHelper.getView(R.id.iv_user_type), model.user_role);
                Utils.setUserRoleText(tvUserType, model.user_role);

                viewHolderHelper.setText(R.id.tv_friend_name, model.display_name);
                viewHolderHelper.setText(R.id.tv_friend_sign, "擅长领域：" + model.getGoodAtString());

                TextView tvInvite = viewHolderHelper.getView(R.id.tv_invite);
                if (model.isSelected) {
                    tvInvite.setText(R.string.invited);
                    tvInvite.setTextColor(ContextCompat.getColor(mContext, R.color.colorGray));
                    tvInvite.setBackgroundResource(R.drawable.round_line_gray);
                } else {
                    tvInvite.setText(R.string.invite);
                    tvInvite.setTextColor(ContextCompat.getColor(mContext, R.color.colorBlueLight));
                    tvInvite.setBackgroundResource(R.drawable.round_line_blue_light);
                }
            }

            @Override
            public void onItemChildClick(View view, int i) {
                if (!((BaseActivity) mActivity).isCanClick(view)) return;
                final User user = mDatas.get(i);
                switch (view.getId()) {
                    case R.id.tv_invite:
                        if (user.isSelected) {
                            return;
                        }

                        HttpUtils.invite(user.user_id, mView.getQuestionId(), new HttpCallback<Object>() {

                            @Override
                            public void onStart() {
                                super.onStart();
                                onStartAsync();
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                onFinishAsync();
                            }

                            @Override
                            public void onSuccess(Object o) {
                                if (mView == null) {
                                    return;
                                }

                                user.isSelected = true;
                                notifyDataSetChanged();
                                ToastUtils.show(mActivity, "已发送邀请");
                            }

                            @Override
                            public void onError(String strMsg) {
                                super.onError(strMsg);
                                if (mView == null) {
                                    return;
                                }
                                showMessage(strMsg);
                            }
                        });

                        break;
                }
            }
        }
    }

}
